import { LoginWayEnum, WxOauthScopeEnum } from "@/enums/appEnums";
import { BACK_URL } from "@/enums/cacheEnums";
import { useAppStore } from "@/store/modules/app";
import { useUserStore } from "@/store/modules/user";
import { isWeixinClient } from "@/utils/client";
import cache from "@/utils/cache";
import wechatOa, { UrlScene } from "@/utils/wechat";
import { getToken } from "@/utils/auth";
const appStore = useAppStore();

interface IOptions {
  accountLoginFormData?: {};
}
const isForceBindMobile = computed(
  () => appStore.getLoginConfig.coerce_mobile == 1
);
export function useLogin(options: IOptions) {
  const userStore = useUserStore();
  const removeWxQuery = () => {
    const url = new URL(window.location.href);
    url.searchParams.delete("code");
    url.searchParams.delete("state");
    window.location.href = url.toString();
  };
  const includesLoginWay = (loginWay: LoginWayEnum) => {
    return appStore.getLoginConfig.loginWay.includes(LoginWayEnum.WX_OA);
  };
  const login = async (loginWay: LoginWayEnum) => {
    if (loginWay === LoginWayEnum.WX_OA) {
      wxGetCodeRedirectUri();
    }
    if (loginWay === LoginWayEnum.ACCOUNT) {
      await accountLogin();
    }
    if (loginWay === LoginWayEnum.SMS) {
      await smsLogin();
    }
    if (isForceBindMobile.value) {
      uni.navigateTo({
        url: "/pages/bindMobile/index",
      });
    }
    await toPrePage();
  };
  const accountLogin = async () => {
    await userStore.login(options.accountLoginFormData);
    await userStore.getUser();
  };
  // 短信登录
  const smsLogin = async () => {};
  // 二维码登录
  const qrLogin = async () => {};

  // 扫码登录
  const qrCodeScanLogin = async () => {};

  // 微信h5code登录
  const wxGetCodeRedirectUri = async () => {
    // 向后端获取微信oauth code链接，redirect到微信授权页面
    // 适用h5端
    try {
      await wechatOa.getUrl(UrlScene.LOGIN);
    } catch (error) {
      console.log(error);
      removeWxQuery();
    }
  };
  async function toPrePage() {
    const pages = getCurrentPages();
    console.log("pages",pages)
    if (pages.length > 1) {
      const prePage = pages[pages.length - 2];
      await uni.navigateBack();
      const options = (prePage as any).options || {};
      prePage.onLoad && prePage.onLoad(options);
    } else if (cache.get(BACK_URL)) {
      try {
        uni.navigateTo({
          url: cache.get(BACK_URL),
        });
      } catch (error) {
        uni.switchTab({ url: cache.get(BACK_URL) });
      }
    } else {
      uni.reLaunch({ url: "/pages/home/index" });
    }
    // cache.remove(BACK_URL);
  }
  async function wxOaLogin() {
    const { code, scene } = wechatOa.getAuthData();
    try {
      if (code && scene === UrlScene.LOGIN) {
        uni.showLoading({
          title: "请稍后",
        });
        userStore
          .login({
            code: code,
            scene: LoginWayEnum.WX_OA,
          })
          .then(() => {
            toPrePage();
          });
      } else {
        await wechatOa.getUrl(UrlScene.LOGIN);
      }
    } catch (error) {
      removeWxQuery();
    } finally {
      uni.hideLoading();
      wechatOa.setAuthData();
    }
  }
  // function wxOaLogin() {
  //   return new Promise(async (resolve, reject) => {
  //     const { code, scene } = wechatOa.getAuthData();
  //     console.log("wxOaLogin params",code,scene)
  //     try {
  //       if (code && scene === UrlScene.LOGIN) {
  //         uni.showLoading({
  //           title: "请稍后",
  //         });
  //         await userStore.login({
  //           code: code,
  //           scene: LoginWayEnum.WX_OA,
  //         });
  //         resolve(true);
  //       }
  //     } catch (error) {
  //       console.log(error);
  //       reject(false);
  //       removeWxQuery();
  //     } finally {
  //       uni.hideLoading();
  //     }
  //   });
  // }

  return {
    wxOaLogin,
    includesLoginWay,
    login,
  };
}
